package com.housekeeping.controller.api;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.housekeeping.model.User;
import com.housekeeping.service.UserService;
import com.housekeeping.service.impl.UserServiceImpl;
import com.housekeeping.utils.ApiResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/api/auth/*")
public class AuthController extends HttpServlet {
    
    private UserService userService = new UserServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        String pathInfo = req.getPathInfo();
        
        try {
            if ("/login".equals(pathInfo)) {
                handleLogin(req, resp);
            } else {
                ApiResponse.sendJsonResponse(req, resp, ApiResponse.error(404, "Not Found"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ApiResponse.sendJsonResponse(req, resp, ApiResponse.error(500, "Internal Error"));
        }
    }
    
    private void handleLogin(HttpServletRequest req, HttpServletResponse resp) 
            throws IOException {
        
        try {
            String requestBody = req.getReader().lines()
                .reduce("", (accumulator, actual) -> accumulator + actual);
            
            Map<String, Object> loginData = objectMapper.readValue(
                requestBody, new TypeReference<Map<String, Object>>() {});
            
            String username = (String) loginData.get("username");
            String password = (String) loginData.get("password");
            
            if (username == null || password == null) {
                ApiResponse.sendJsonResponse(req, resp, ApiResponse.error(400, "Missing credentials"));
                return;
            }
            
            User user = userService.login(username, password);
            if (user != null) {
                HttpSession session = req.getSession(true);
                session.setAttribute("user", user);
                user.setPassword(null);

                String token = session.getId();
                Map<String, Object> result = new java.util.HashMap<>();
                result.put("token", token);
                result.put("user", user);
                ApiResponse.sendJsonResponse(req, resp, ApiResponse.success(result));
            } else {
                ApiResponse.sendJsonResponse(req, resp, ApiResponse.error(401, "Invalid credentials"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ApiResponse.sendJsonResponse(req, resp, ApiResponse.error(400, "Invalid request"));
        }
    }
} 